package com.hxut.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import java.io.IOException;

@WebFilter(filterName = "EncodingFilter",urlPatterns = "/*",initParams = {@WebInitParam(name = "Encoding",value = "UTF-8")})
public class EncodingFilter implements Filter {
    String encoding ;

    public String getEncoding() {
        return encoding;
    }

    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
         String value = filterConfig.getInitParameter("Encoding");
         setEncoding(value);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //设置请求的编码格式
        servletRequest.setCharacterEncoding(encoding);
        //设置响应的编码格式
        servletResponse.setContentType("text/html;charset="+getEncoding());
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
